package com.uwin.findTomcat;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

@SuppressWarnings("serial")
public class PsCmd implements Serializable {

	public static final String PS_CMD = "ps -eo pid,%mem,command|grep www/tomcat";
	public static final String NETSTAT_CMD = "netstat -nltp|grep %s";
	public static final String MEM_REG = "\\s+\\d+\\.\\d+\\s+";
	private String pid;
	private String raw;
	private String mem;
	private String tomcatName;
	private String tomcatPath;
	private String addresses;
	
	private Boolean isTomcat = true;
	
	
	public static PsCmd resolve(String str,RemoteExecuteCommand rec){
		
		if (str.indexOf("org.apache.catalina")<0) {
			return null;
		}
		str = str.trim();
		PsCmd psCmd = new PsCmd();
		psCmd.setRaw(str);
		try {
			
			int pidSplit =  str.indexOf(" ");
			String pid = str.substring(0, pidSplit);
			String tomcatPath = str.substring(str.indexOf("/www/tomcat/"),str.indexOf("/conf/logging.properties"));
			String tomcatName = tomcatPath.substring( tomcatPath.lastIndexOf("/") +1);

			if (StringUtils.isBlank(tomcatName) || StringUtils.isBlank(pid)
					|| StringUtils.isBlank(tomcatPath)) {
				
				throw new Exception("不是规范的tomcat进程，无法解析");
			}
			
			psCmd.setPid(pid);
			psCmd.setTomcatName(tomcatName);
			psCmd.setTomcatPath(tomcatPath);
			psCmd.setMem(regMem(str) + "%");
			
			List<String> addresses = rec.executeSuccessList(String.format(NETSTAT_CMD, pid));
			
			StringBuffer sb = new StringBuffer();
			for(String address : addresses){
				sb.append(resolveAddress(address)).append(",");
			}
			
			if (sb.length() >0 ) {
				sb.deleteCharAt(sb.length()-1);
				psCmd.setAddresses(sb.toString());
			}

		} catch (Exception e) {
			psCmd.isTomcat = false;
			return psCmd;
		}
		return psCmd;
	}
	
	public static String resolveAddress(String address) {
	//	String tString = "tcp6       0      0 :::9089                 :::*                    LISTEN      6407/java";
		String reg = ":\\d+\\s";
		String result = null;
		Pattern pattern = Pattern.compile(reg);
		Matcher matcher = pattern.matcher(address);
		if (matcher.find()){
			result = matcher.group().trim().substring(1);
		}
		return result;
	}
	
	public static List<PsCmd> resolves(RemoteExecuteCommand rec){
		
		List<PsCmd> psCmds = new ArrayList<>();
		
		List<String> executeResult = rec.executeSuccessList(PS_CMD);
		
		PsCmd psCmd = null;
		for (String result : executeResult) {
			psCmd = resolve(result,rec);
			if (psCmd != null && psCmd.getIsTomcat()) {
				psCmds.add(psCmd);
			}
		}
		
		return psCmds;
	}
	
	public static String regMem(String str) {
		
		//String tString  = "6407  4.9 /usr/lib/jvm/jdk1.7.0_67/jre/bin/java -Djava.util.logging.config.file=/www/tomcat/tomcat7_split_impl/conf/logging.properties -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djdk.tls.ephemeralDHKeySize=2048 -Djava.endorsed.dirs=/www/tomcat/tomcat7_split_impl/endorsed -classpath /www/tomcat/tomcat7_split_impl/bin/bootstrap.jar:/www/tomcat/tomcat7_split_impl/bin/tomcat-juli.jar -Dcatalina.base=/www/tomcat/tomcat7_split_impl -Dcatalina.home=/www/tomcat/tomcat7_split_impl -Djava.io.tmpdir=/www/tomcat/tomcat7_split_impl/temp org.apache.catalina.startup.Bootstrap star";
		
		Pattern pattern = Pattern.compile(MEM_REG);
		Matcher matcher = pattern.matcher(str);
		matcher.find();
		return matcher.group().trim();
/*		StringBuffer stringBuffer = new StringBuffer();
		stringBuffer.append("123456789");
		stringBuffer.deleteCharAt(stringBuffer.length()-1);
		System.out.println(stringBuffer.toString());*/
	}

	public String getPid() {
		return pid;
	}

	public void setPid(String pid) {
		this.pid = pid;
	}

	public String getRaw() {
		return raw;
	}

	public void setRaw(String raw) {
		this.raw = raw;
	}

	public String getTomcatName() {
		return tomcatName;
	}

	public void setTomcatName(String tomcatName) {
		this.tomcatName = tomcatName;
	}

	public String getTomcatPath() {
		return tomcatPath;
	}

	public void setTomcatPath(String tomcatPath) {
		this.tomcatPath = tomcatPath;
	}

	public String getAddresses() {
		return addresses;
	}

	public void setAddresses(String addresses) {
		this.addresses = addresses;
	}

	public Boolean getIsTomcat() {
		return isTomcat;
	}

	public void setIsTomcat(Boolean isTomcat) {
		this.isTomcat = isTomcat;
	}

	public String getMem() {
		return mem;
	}

	public void setMem(String mem) {
		this.mem = mem;
	}
	
}